package org.codetranslators.compiler.liveness;

import java.util.Vector;

public class Graph
{
	private int nodeCount;
	private Vector<Node> nodes;    // nodes in this graph

	public Graph(int size)
	{
		nodes = new Vector(size);
		//Initialize the nodes list with nulls
		for(int i = 0; i < size; i++)
		{
			nodes.addElement(null);
		}
	}

	public Vector nodes()
	{
		return nodes;
	}

	public Node newNode(String id)
	{
		return new Node(this, id);
	}

	public void addNode(Node n, int index)
	{
		if(index <= nodes.size()-1)
			nodes.set(index, n);
		else
			nodes.addElement(n);
		//nodes.add(index, n);
	}

	public void addEdge(Node from, Node to)
	{
	    if (from.goesTo(to)) return;   // if there is already an edge, do not add one

	    to.addToPredecessorList(from);
	    from.addToSuccessorList(to);
	}

	public boolean delete(Node node, Vector nodeList)
	{
		int numNodes = nodeList.size();
		Node nodeFound = null;
		for(int i = 0; i < numNodes; i++)
		{
			nodeFound = (Node) nodeList.elementAt(i);
			if(nodeFound == node) break;
		}

		if(nodeFound != null)
		{
			return nodeList.remove(nodeFound);
		}
		return false;
	 }

	 public boolean rmEdge(Node from, Node to)
	 {
		 boolean b1 = delete(from, to.getPredecessors());
		 boolean b2 = delete(to, from.getSuccessors());
		 return b1 && b2;
	 }

	 public int getNodeCount()
	 {
		 return nodeCount;
	 }

	 public void incrementNodeCount()
	 {
		 nodeCount++;
	 }

	 public void show(java.io.PrintStream out)
	 {
		 for(int i = 0; i < nodeCount; i++)
		 {
			 Node n = (Node) nodes.elementAt(i);
			 out.print(n.toString());
			 out.print(": ");

			 // Print successors
			 Vector succs = n.getSuccessors();
			 int numSuccs = succs.size();
			 for(int j = 0; j < numSuccs; j++)
			 {
				 Node succ = (Node) succs.elementAt(j);
			     out.print(succ.toString());
			     out.print(" ");
			  }
			 out.println();
		 }
	 }
}
